/*
 * @Date: 2020-08-24 16:18:04
 * @LastEditors: xujianxing
 * @LastEditTime: 2020-08-24 17:57:30
 * @FilePath: \nili\src\common\pipe\validation.pipe.ts
 * 参数类型校验
 */
import {
  PipeTransform,
  ArgumentMetadata,
  Injectable,
  BadRequestException,
} from '@nestjs/common';
import { validate } from 'class-validator';
import { plainToClass } from 'class-transformer';

@Injectable()
export class ValidationPipe implements PipeTransform<any> {
  async transform(value: any, { metatype }: ArgumentMetadata) {
    /** 不是JavaScript类型，不进行验证 */
    if (!metatype || !this.toValidate(metatype)) {
      return value;
    }

    const object = plainToClass(metatype, value);
    const errors = await validate(object);
    if (errors.length > 0) {
      throw new BadRequestException('validate failed');
    }
    return value;
  }

  /** 验证类型是否是 JavaScript */
  private toValidate(metatype: Function): boolean {
    const types: Function[] = [String, Boolean, Number, Array, Object];
    return !types.includes(metatype);
  }
}
